import React, {Component} from 'react';
import {Route} from 'react-router-dom';
import routes from './routes';
import List from '../List';
import {Select, Row, Col, Icon, Menu, Dropdown, Button, Spin, message} from 'antd';
import {connect} from '../../utils/decorator';
import Setting from '../../components/Setting';
import Back from '../../components/Back';
import {getEnvPath, login} from '../../utils';
import style from './style.less';

const Option = Select.Option;
const routeData = [{
    path:'/',
    component:List
}].concat(routes)

@connect
class Home extends Component {

    state = {
        loading:false,
        showBack:false,
        realname:'',
        accounts:[],
        accountId:'', 
        period:''
    }

    componentDidMount(){
        const {users} = this.props.data;
        this.initData(users);
        this.unListen = this.props.history.listen(location => {
            this.setState({
                showBack:location.pathname !== '/'
            })
        })
    }

    initData = (users)=>{
        if(!users[0]){
            this.request.abort()
            location.hash = '/login'
        }
        else{
            const user = users.find(v => {
                return v.active === true
            })
            if(!user.realname){
                this.request('getUserInfo')
                    .then(res => {
                        if(res.clouduser){
                            const {realname} = res.clouduser;
                            users = users.map(v => {
                                if(v.active === true){
                                    v.realname = realname
                                }
                                return v
                            })
                            this.setState({
                                realname
                            }, () => {
                                this.props.dispatch({
                                    type:'user/change',
                                    data:{
                                        users
                                    }
                                })
                                this.updateAccounts(users)
                            })
                        }
                    })
            }
            else{
                this.setState({
                    realname:user.realname
                }, () => {
                    this.updateAccounts(users)
                })
            }
        }
    }

    updateAccounts = (users)=>{
        this.request('getAccountList')
            .then(res => {
                this.props.dispatch({
                    type:'user/change',
                    data:{
                        users:users.map(v => {
                            if(v.active === true){
                                let accounts = res.data || [];
                                let accountId = '', period = '';
                                const accountData = v.accounts || [];
                                const defaultAccount = accountData.find(v => {
                                    return v.active === true
                                })
                                const ids = {};
                                //先去重
                                accounts = accounts.filter(v => {
                                    if(!ids[v.accID]){
                                        ids[v.accID] = true
                                        return true
                                    }
                                    return false
                                })
                                if(defaultAccount){
                                    accounts = accounts.map(v => {
                                        if(v.accID === defaultAccount.accID){
                                            accountId = v.accID;
                                            period = v.statePeriod;
                                            v.active = true
                                        }
                                        return v
                                    })
                                }
                                else if(accounts[0]){
                                    accountId = accounts[0].accID;
                                    period = accounts[0].statePeriod;
                                }
                                this.setState({
                                    loading:false,
                                    accountId,
                                    period,
                                    accounts
                                })
                                v.accounts = accounts
                            }
                            return v
                        })
                    }
                })
            }).catch(() => {
                this.setState({
                    loading:false
                })
            })
    }

    selectAccount = (value, option)=>{
        const {period} = option.props;
        this.setState({
            accountId:value, 
            period
        }, () => {
            const {users} = this.props.data;
            this.props.dispatch({
                type:'user/change',
                data:{
                    users:users.map(v => {
                        if(v.active === true){
                            v.accounts = v.accounts.map(_v=>{
                                _v.active = value === _v.accID
                                return _v
                            })
                        }
                        return v
                    })
                }
            })
        })
    }

    changeUser = (data)=>{
        this.setState({
            loading:true
        })
        login(data).then((users) => {
            this.initData(users)
        }).catch(err => {
            message.error(err)
            this.setState({
                loading:false
            })
        })
    }

    login = ()=>{
        const {users} = this.props.data;
        const {accountId} = this.state;
        const domain = localStorage.getItem('domain');
        const website = localStorage.getItem('website');
        if(!accountId && website == 2){
            message.error('请选择账套')
            return
        }
        const data = users.find(v => {
            return v.active === true
        })
        chrome.tabs.query({active:true}, function(tabs){
            const source = {
                ...data,
                accountId,
                domain,
                website
            }
            chrome.tabs.sendMessage(tabs[0].id, {message:source}, function(response){
                if(response === 'wait'){
                    setTimeout(() => {
                        chrome.tabs.sendMessage(tabs[0].id, {message:source})
                    }, 1000)
                }
            })
        })
    }

    componentWillUnmount(){
        this.unListen()
    }

    render(){
        const {showBack, accounts, accountId, period, loading, realname} = this.state;
        const {users} = this.props.data;
        const envPath = getEnvPath();
        return (
            <Spin tip="登录中..." spinning={loading}>
                <div className={style.box}>
                    <div className={style.head}>
                        <Row type="flex" justify="space-between">
                            <Col>
                                <b>当前帐套</b>
                                <span style={{fontSize:12, marginLeft:8}}>会计期间：{period}</span>
                            </Col>
                            <Col>
                                {showBack && <Back />}
                            </Col>
                        </Row>
                        <Select 
                            value={accountId} 
                            showSearch 
                            optionFilterProp="children"
                            onSelect={this.selectAccount} 
                            style={{width:'100%'}}>
                            {
                                accounts.map(v => {
                                    return (
                                        <Option key={v.accID} period={v.statePeriod}>{v.accountName}</Option>
                                    )
                                })
                            }
                        </Select>
                    </div>
                    <div className={style.body}>
                        {routeData.map(v=>{
                            return <Route {...v} key={v.path} replace exact />
                        })}
                    </div>
                    <Row type="flex" justify="space-between" className={style.foot}>
                        <Col>
                            <Dropdown overlay={(
                                <Menu className={style.menu}>
                                    {
                                        users.filter(v => {
                                            return v.envPath === envPath
                                        }).map((v, i) => {
                                            return (
                                                <Menu.Item key={i} onClick={()=>this.changeUser(v)} className={v.active ? 'active' : ''}>
                                                    <a>
                                                        <span>{v.realname}</span>
                                                    </a>
                                                </Menu.Item>
                                            )
                                        })
                                    }
                                </Menu>
                            )}>
                                <span>
                                    <Icon type="user" style={{fontSize:20, verticalAlign:'middle'}} />
                                    <b style={{verticalAlign:'middle'}} className={style.username}>{realname}</b>
                                </span>
                            </Dropdown>
                            <Button type="primary" size="small" style={{verticalAlign:'middle', marginLeft:16}} onClick={this.login}>登录网页</Button>
                        </Col>
                        <Col>
                            <Setting />
                        </Col>
                    </Row>
                </div>
            </Spin>
        )
    }
}

export default Home